//
//  ViewController.m
//  第六章节的Demo
//
//  Created by clz on 2019/9/22.
//  Copyright © 2019 clz. All rights reserved.
//

#import "ViewController.h"
#import <Masonry.h>
#import "TestCell.h"
#import "TestCellWihtXIB.h"
#import <AFNetworking.h>
#import "TestModel.h"
#import <MJRefresh.h>
#import "DataManger.h"


@interface ViewController ()<UITableViewDelegate,UITableViewDataSource>

@property(nonatomic,strong)UITableView *tableView;

@property(nonatomic,strong)NSMutableArray *dataArray;

@property(nonatomic,assign)NSInteger pageIndex;

@property(nonatomic,strong)UILabel *titleLabel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.titleLabel = [[UILabel alloc]init];
    self.titleLabel.text = NSLocalizedString(@"title", nil);
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.font = [UIFont systemFontOfSize:18];
    self.titleLabel.textColor = [UIColor blackColor];
    [self.view addSubview:self.titleLabel];
    [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.top.equalTo(self.view);
        make.height.mas_equalTo(44);
    }];
    
    
    self.pageIndex = 1;
    
    //使用cocoapods 第一步要创建podfile文件
    
    //cell的定制
   //开发UI的核心
    self.dataArray = [[NSMutableArray alloc]init];
    
    self.tableView = [[UITableView alloc]init];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.view addSubview:self.tableView];
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    } else {
        
    }
    
    //我们一般不会用frame去固定位置
    [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
       //在这里写约束
        make.left.equalTo(self.view);
        make.right.equalTo(self.view);
        make.bottom.equalTo(self.view);
        make.top.equalTo(self.titleLabel.mas_bottom);
    }];
    
    //注册cell
    [self.tableView registerClass:[TestCell class] forCellReuseIdentifier:@"TestCell"];
    
    [self.tableView registerNib:[UINib nibWithNibName:@"TestCellWihtXIB" bundle:nil] forCellReuseIdentifier:@"TestCellWihtXIB"];
    
    
    __weak typeof(self) weakSelf = self;
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.pageIndex = 1;
        [weakSelf requestData];
    }];
    
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
        weakSelf.pageIndex++;
        [weakSelf requestData];
    }];
    
    
    //
    //主线程
    //子线程
    /*
     车 -> 口 过收费口 (8辆车排队)
     
     //现在我们开了8个子线程,就有了8个收费口
     //把每一辆车分配到一个收费口
     
     
     
     */
    
    //获取网络数据
    //AFNetworking
//    [self requestData];

    
    [self.tableView.mj_header beginRefreshing];
    
    //每一个app都有自己的文件目录
    //所有的app的目录都不可以相互访问
    //ios8之前
    //沙盒根目录
    NSString *homePath = NSHomeDirectory();
    NSLog(@"homePath = %@",homePath);
    
    //持久化
    //账号和密码
    //plist
    //数据比较多的话，就使用本地数据库  sqlite FMDB
    //coreData
   
    //document目录
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    NSLog(@"documentPath = %@",documentPath);
    
    
    NSString *account = @"user01";
    NSString *password = @"123456";
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setValue:account forKey:@"user_account"];
    [userDefault setValue:password forKey:@"user_password"];
    [userDefault synchronize];
    NSString *user_account = [userDefault objectForKey:@"user_account"];
    NSString *user_password = [userDefault objectForKey:@"user_password"];
    NSLog(@"user_account = %@",user_account);
    NSLog(@"user_password = %@",user_password);
    
//    [self savePlistData];
    
//    [self getPlistData];
    
    
//    [[DataManger sharedInstance] insertDataWithName:@"xiaowang" age:20 height:175];
    NSInteger age = [[DataManger sharedInstance]queryDataWithName:@"xiaowang"];
    NSLog(@"年龄 = %ld",(long)age);
    
    //国际化
    
}

- (void)savePlistData{
    NSDictionary *userInfo = @{
                               @"name":@"xiaowang",
                               @"age":@"18",
                               @"height":@"180"
                               };
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"userInfo.plist"];
    
    [userInfo writeToFile:filePath atomically:YES];
}

- (void)getPlistData{
    
    NSString *documentPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).firstObject;
    
    NSString *filePath = [documentPath stringByAppendingPathComponent:@"userInfo.plist"];

    NSDictionary *tempData = [NSDictionary dictionaryWithContentsOfFile:filePath];
    
    NSLog(@"tempData = %@",tempData);
    
}



- (void)requestData{
    
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    
    session.securityPolicy.allowInvalidCertificates = YES;
    
    session.operationQueue.maxConcurrentOperationCount = 5;
    
    session.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/plain", @"text/html",@"image/jpeg", nil];
    
    [session.requestSerializer setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
    
    session.requestSerializer.timeoutInterval = 10;
    
    //GET 和 POST
    NSString *url = @"http://tools.popsage.com/web/getItemListByGroupId";
    //json
    NSDictionary *parameters = @{
                                        @"groupId":@"1",
                                        @"pageIndex":@(self.pageIndex),
                                        @"pageSize":@"10"
                                        };
    __weak typeof(self) weakSelf = self;
    [session GET:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"responseObject = %@",responseObject);
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];
        
        if (weakSelf.pageIndex == 1) {
            [weakSelf.dataArray removeAllObjects];
        }
        
        id data = responseObject[@"data"];
        for (NSDictionary *dic in data) {
            TestModel *model = [[TestModel alloc]init];
            [model setValueWithData:dic];
            [weakSelf.dataArray addObject:model];
        }
        [weakSelf.tableView reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败了");
        [weakSelf.tableView.mj_header endRefreshing];
        [weakSelf.tableView.mj_footer endRefreshing];

    }];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row > 4) {
        
        TestCellWihtXIB *cell = [tableView dequeueReusableCellWithIdentifier:@"TestCellWihtXIB" forIndexPath:indexPath];
        
        TestModel *model = self.dataArray[indexPath.row];
        
        cell.testTitleLabel.text = model.zh;
        cell.subTestTitleLabel.text = model.en;


        return cell;

        
    }else{
        
        TestCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TestCell" forIndexPath:indexPath];
        
        TestModel *model = self.dataArray[indexPath.row];
        
        cell.testTitleLabel.text = model.zh;
        cell.subTestTitleLabel.text = model.en;

        return cell;

    }
    
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 120;
}




@end
